<!--
 * @Description: 分解目标成本数据
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2024-03-01 18:34:04
 * @LastEditTime: 2024-03-12 09:43:30
 * @FilePath: \cscec-pms-admin\src\views\businessAffairs\businessCostPlanManagement\costPlanManagement\costPlan\components\InformationInit\components\DecompositionData\index.vue
-->
<template>
  <div class="table-wrapper">
    <u-table
      ref="table"
      fixed-columns-roll
      :height="height"
      show-header-overflow
      :tree-config="{
        children: 'children',
        expandAll: true
      }"
      row-id="id"
      :use-virtual="true"
      border
      :row-height="40"
    >
      <u-table-column
        v-for="item in columns"
        :key="item.dataIndex"
        :prop="item.dataIndex"
        :label="item.title"
        :width="item.width"
        :minWidth="item.minWidth"
        :fixed="item.fixed"
        :tree-node="item.dataIndex === 'name'"
        align="left"
      >
        <template v-slot="{ row }">
          <template v-if="(row.yearMonths || []).findIndex((el) => el.key === item.dataIndex) >= 0">
            <!-- //row.thisAddMonthList.includes(item.dataIndex) 有就可以编辑,isAdd-->
            <p v-if="((row.children || []).length > 0 || !row.thisAddMonthList.includes(item.dataIndex)) && !isAddFn(item.dataIndex, row) && getYearMonth(item.dataIndex, row)" :title="row.detailValues[item.dataIndex]">
              {{ row.detailValues[item.dataIndex] | setPlaceholder}}
            </p>
            <!-- onKeyPress="if((event.keyCode<48 || event.keyCode>57) && event.keyCode!=46 || /\.\d\d$/.test(value))event.returnValue=false" -->
            <input class="input-style" v-else-if="(row.children || []).length == 0 " type="number" v-model="row.detailValues[item.dataIndex]" @input="handleUpdate(row, item.dataIndex, item.dataIndex)" />
              <p v-else>{{ row.detailValues[item.dataIndex] | setPlaceholder }}</p>
          </template>
          <template v-else-if="item.dataIndex === 'description'">
            <BaseInput v-model="row[item.dataIndex]" @blur="handleUpdate(row, item.dataIndex)" />
          </template>
          <p v-else :title="row[item.dataIndex]">{{ row[item.dataIndex] | setPlaceholder }}</p>
        </template>
      </u-table-column>
    </u-table>
  </div>
</template>
  <script>
import { UTable, UTableColumn } from 'umy-ui'
import { columns } from './model.js'
import { addOrUpdateProjectTreeDetail, submit } from '@/api/businessAffairs/costAccountInit'
import { getCostPlan as queryPlan } from '@/api/businessAffairs/InformationAdjustment'
import debounce from 'lodash/debounce'
import { publicMixin } from './../../../public'
import { placeholder } from '../../../../../../headquartersDashboard/components/placeholderWay.js'
import moment from 'moment'
export default {
  name: 'DecompositionData',
  mixins: [publicMixin], //混入文件
  components: {
    UTable,
    UTableColumn
  },
  props: ['id'],
  data() {
    return {
      value: null,
      editable: false,
      // 表格高度
      height: 0,
      // 表格数据
      data: [],
      // 表格数据映射
      dataMap: new Map(),
      // 表头
      columns: this.$clone(columns),
      // 动态表头
      activeColumns: [],
      // 当前项目id
      projectId: this.$userInfo()?.currentPost?.projectId,
      // 业务id
      businessId: ''
    }
  },
  mounted() {
    this.height = document.querySelector('.table-wrapper').offsetHeight
    this.getTableData()
  },
  filters:{
    setPlaceholder(val){
      return placeholder(val)
    }
  },
  methods: {
    // 校验 isAdd 为1可以编辑
    isAddFn(month, row) {
      let findMothObj = {}
      if (row?.details && row?.details?.length > 0) {
        findMothObj = row?.details.find((item) => item.yearMonthNum == month)
        if (findMothObj?.isAdd * 1 === 1) {
          // console.log(findMothObj,1111)
          return true
        } else {
          return false
        }
      } else {
        return false
      }
    },
    //比较时间
    getYearMonth(oldMonth, row) {
      let flag = row.level * 1 === 2 && row?.children?.length > 0 //子级是临时节点，则父级不能编辑
      const oldMonthFn = (str) => str.replace(/^(.{4})/, '$1/')
      const now = moment(),
        newMonth = now.format('YYYY/MM'),
        oldMonthData = oldMonthFn(oldMonth),
        oldMonthTime = new Date(oldMonthData),
        newMonthTime = new Date(newMonth)
      if (oldMonthTime.getTime() <= newMonthTime.getTime()) {
        return true
      } else {
        if (flag) {
          return true
        } else {
          return false
        }
      }
    },
    /**
     * @description: 扁平化树
     * @param {array} tree 树
     * @return {void}
     */
    flattenTree(tree) {
      for (let i = 0; i < tree.length; i++) {
        this.dataMap.set(tree[i].id, tree[i])
        if (tree[i]?.childTree && tree[i].childTree?.length > 0) {
          this.flattenTree(tree[i].childTree)
        }
      }
    },
    /**
     * @description: 获取表格数据
     * @return {void}
     */
    getTableData() {
      this.$emit('update:spinning', true)
      queryPlan({
        id: this.id,
        isHide: true
      })
        .then((res) => {
          if (res.code === '0') {
            this.businessId = res.data.id
            this.data = res.data?.trees
            // this.reloadData(this.data)
            this.activeColumns = res.data.yearMonths.map((el) => {
              return {
                title: el.title,
                width: 150,
                dataIndex: el.key
              }
            })
            const col = this.$clone(columns)
            const end = col.pop()
            this.columns = [...col, ...this.activeColumns, end]
            this.$nextTick(() => {
              this.summation(this.data,this.activeColumns)
              this.reloadData(this.data)
            })
          }
        })
        .finally(() => {
          this.$emit('update:spinning', false)
        })
    },
    /**
     * @description: 加载数据
     * @param {array} data
     * @return {void}
     */
    reloadData(data , isShow =  true) { 
      this.flattenTree(data)
      // 获取之前展开数据
      const expandRecords = this.$refs.table.getTreeExpandRecords()
      // 获取之前滚动高度(表格实例上的scrollTop属性，在滚动到底部时会小于真实的scrollTop值，因此直接从dom获取真实滚动高度)
      const scrollTop = this.$refs.table.tableExample().bodyWrapper.scrollTop
      const scrollLeft = this.$refs.table.tableExample().bodyWrapper.scrollLeft
      // 加载数据
      
      this.$refs.table.reloadData(data).then(() => {
        // 清除之前展开行信息
        !isShow &&  this.$refs.table.clearTreeExpand()
        // 数据加载完成出现之后，打开之前的展开行
        expandRecords.forEach((row) => {
          this.$refs.table.setTreeExpansion(row, true)
        })
        this.$refs.table.pagingScrollTopLeft(scrollTop, scrollLeft)
      })
    },

    /**
     * @description: 编辑
     * @param {object} row 行数据
     * @param {string} blurIndex 失焦字段
     * @return {void}
     */
    handleUpdate: debounce(function (row, blurIndex, key) {
      console.log(row, blurIndex, key)
      if (blurIndex != 'description') {
        row.detailValues[blurIndex] = row.detailValues[blurIndex]?.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
      }
      addOrUpdateProjectTreeDetail(
        blurIndex === 'description'
          ? {
              id: row.id,
              description: row.description
            }
          : {
              amount: row.detailValues[blurIndex],
              id: row.id,
              yearMonthNum: blurIndex,
              isAdd: 1,
              yearMonthStr: this.moment(blurIndex).format('YYYY年MM月')
            }
      )
      if (key) {
        let changeTreeData = this.changeTreeDataTwo(this.data, row, key)
        this.$nextTick(() => {
          this.reloadData(changeTreeData,false)
        })
      }
    }, 500),
    /**
     * @description: 提交
     * @return {void}
     */
    handleSubmit() {
      return new Promise((resolve, reject) => {
        this.$emit('update:spinning', true)
        submit(this.businessId)
          .then((res) => {
            if (res.data.length === 0) {
              this.$emit('update:spinning', false)
              resolve()
            } else {
              this.$emit('update:spinning', false)
              reject(res.data)
            }
          })
          .catch((err) => {
            console.log(err)
            this.$emit('update:spinning', false)
            reject(err)
          })
      })
    }
  }
}
</script>
  <style lang="less" scoped>
.input-style {
  width: 100%;
  height: 30px;
  padding: 0 11px;
  text-align: left;
  background-color: transparent;
  border: 0;
  border-radius: 2px;
  outline: 0;
  border: 1px solid #d9d9d9;
}
.input-style:focus {
  border: 1px solid #40a9ff;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
  /* 针对Firefox */
input[type=number] {
  -moz-appearance: textfield;
}
</style>
  